<?php
namespace Qgs\Controller;

use Think\Model;
use Home\Event\JssdkEvent;
use Qgs\Model\SpecialViewModel;

class SpecialController extends BaseController {

    /**
     * 专题首页 专题列表
     */
    public function index() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[] = ' 1=1 ';
        $where[] = array('local_id' => session('userInfo')['local_id']);
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_special_store')->where($where)->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = 'a.id,a.title,a.title2,a.title3,a.idx,a.state,a.source,a.create_time,a.update_time, b.title btitle,b.title2 btitle2,b.title3 btitle3';
        $data = M('b2c_special_store')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_special_template b on a.tid=b.id', 'LEFT')
            ->field($fields)
            ->page($p, $num)
            ->where($where)
            ->order($order)
            ->select();
        if ($data) {
            foreach ($data as &$item) {
                if ($item['btitle']) {
                    $item['title'] = $item['btitle'];
                }
                if ($item['btitle2']) {
                    $item['title2'] = $item['btitle2'];
                }
                if ($item['btitle3']) {
                    $item['title3'] = $item['btitle3'];
                }
            }
        }
        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 模板列表
     */
    public function template() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[0] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_special_template')->where($where)->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = 'id,title,title2,title3,create_time';
        $data = M('b2c_special_template')
            ->field($fields)
            ->page($p, $num)
            ->where($where)
            ->order($order)
            ->select();
        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 增加专题 基于模板的编辑
     */
    public function add() {
        $template_id = I('get.template_id');
        if (!$template_id) {
            $this->error('参数缺失');
        }
        $info = M('b2c_special_template')->where(array('id'=>$template_id))->find();
        $this->assign('info', $info);
        $this->display('edit');

    }

    /**
     * 编辑模板
     */
    public function edit() {
        if (IS_POST) {
            $id = I('post.id');
            $template_id = I('post.template_id');
            if (strtotime(date('Y-m-d H:i',strtotime(I('post.start_time')))) > strtotime(date('Y-m-d H:i',strtotime(I('post.end_time'))))) {
                $this->error('开始时间不能大于介绍时间');
            }
            if ($id) {
                $save = array(
                    'content'=> I('post.content'),
                    'typeids' => serialize(I('post.typeids')),
                    'idx' => I('post.idx'),
                    'state' => I('post.state'),
                    'update_time' => time(),
                    'start_time' => strtotime(date('Y-m-d H:i',strtotime(I('post.start_time')))),
                    'end_time' => strtotime(date('Y-m-d H:i',strtotime(I('post.end_time')))),
                    'price_desc' => I('post.price_desc'),
                );
                $res = M('b2c_special_store')->where(array('id'=>$id))->save($save);
            } else {
                $template_info = M('b2c_special_template')->where(array('id'=>$template_id))->find();
                $template_info['tid'] = $template_info['id'];
                unset($template_info['id']);
                $add = array(
                    'local_id' => session('userInfo')['local_id'],
                    'content'=> I('post.content'),
                    'typeids' => serialize(I('post.typeids')),
                    'idx' => I('post.idx'),
                    'state' => I('post.state'),
                    'create_time' => time(),
                    'start_time' => strtotime(date('Y-m-d H:i',strtotime(I('post.start_time')))),
                    'end_time' => strtotime(date('Y-m-d H:i',strtotime(I('post.end_time')))),
                    'price_desc' => I('post.price_desc'),
                );
                $add = array_merge($template_info, $add);
                $res = M('b2c_special_store')->add($add);
            }
            if ($res !== false) {
                //get_curl(session('userInfo')['local_id']);
                redirect(U('special/index'));
                exit();
            } else {
                $this->error();
            }
        } else {
            $id = I('get.id');
            $template_id = I('get.template_id');
            if (empty($template_id) && empty($id)) {
                $this->error('参数缺失');
            }
            if($id) {
                $fields = 'a.id,a.tid,a.local_id,b.title,b.title2,b.title3,b.title4,b.title5,b.img_url,b.ico_url,b.type,';
                $fields .= 'a.content,a.typeids,a.create_time,a.update_time,a.idx,a.state,a.source,a.start_time,a.end_time,a.price_desc';
                $info = M('b2c_special_store a')
                    ->join(C('DB_PREFIX').'b2c_special_template b on a.tid=b.id')
                    ->field($fields)
                    ->where(array('a.id'=>$id))
                    ->find();
                if (empty($info)) {
                    $info = M('b2c_special_store')->where(array('id'=>$id))->find();
                }
                $info['typeids'] = unserialize($info['typeids']);
            } else {

                $info = M('b2c_special_template')->where(array('id'=>$template_id))->find();
                $info['template_id'] = $info['id'];
                unset($info['id']);
            }
            $cartList = M('b2c_special_type_store')->where(array('local_id'=>session('userInfo')['local_id']))->select();
            $this->assign('info', $info);
            $this->assign('cartList', $cartList);
            $this->display();
        }
    }

    /**
     * 专题分类列表 (里面是专题商品)
     */
    public function cart() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'type_id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[] = ' 1=1 ';
        $local_id = session('userInfo')['local_id'];
        $where[] = array('local_id' => $local_id);
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_special_type_store')->where($where)->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = '';
        $list = M('b2c_special_type_store')
            ->field($fields)
            ->where($where)
            ->order($order)
            ->page($p, $num)
            ->select();
        foreach ($list as &$item) {
            if (!$item['goodids']) {
                $item['num'] = 0;
            } else {
                $item['num'] = count(unserialize($item['goodids']));
            }
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function addCart() {
        $this->display('editCart');
    }

    /**
     * 更新或者是新增专题分类
     */
    public function editCart() {
        if (IS_POST) {
            $type_id = I('post.type_id');
            $type_name = I('post.type_name');
            $local_id = session('userInfo')['local_id'];
            $ids = I('post.store_pid');
            if ($ids) {
                $ids = serialize($ids);
            }
            if (!$type_name || !$local_id) {
                $this->error('缺少参数');
            }
            if ($type_id) {
                //更新数据
                $save = array(
                    'type_name' => $type_name,
                    'goodids' => $ids,
                );
                $res = M('b2c_special_type_store')->where(array('type_id'=>$type_id))->save($save);

            } else {
                //新增数据
                $add = array(
                    'local_id' => $local_id,
                    'type_name' => $type_name,
                    'goodids' => $ids,
                );
                $res = M('b2c_special_type_store')->add($add);
            }
            if ($res !== false) {
                redirect(U('special/cart'));
            } else {
                $this->error('失败');
            }
            exit;

        } else {
            $type_id  = I('get.type_id');
            $where = array('type_id'=> $type_id);
            $info = M('b2c_special_type_store')->where($where)->find();
            $list = array();
            if ($info['goodids'] && $ids = unserialize($info['goodids'])) {

                $list = M('b2c_store_product a')
                    ->join(C('DB_PREFIX').'b2c_products b on a.product_id=b.product_id')
                    ->field('a.store_pid, a.store, a.price, b.name')
                    ->where(array('store_pid'=>array('in',$ids)))
                    ->order("FIELD (`store_pid`, ".implode(',', $ids).")")
                    ->select();
                $temp = array_column($list, 'store_pid');
                $ids_str = join('#', $temp);
            }
            $this->assign('info', $info);
            $this->assign('list', $list);
            $this->assign('s_pids', $ids_str);
            $this->display('editCart');
        }
    }

    public function del() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $ids = I('post.id');

        if (is_array($ids)) {
            $ids = join(',', $ids);
        }
        $res = M('b2c_special_store')->delete($ids);
        if ($res !== false) {
            get_curl(session('userInfo')['local_id']);
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    public function delCart() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $ids = I('post.id');
//        $ids = $data['id'];
//        if (is_array($ids)) {
//            $ids = join(',', $ids);
//        }
        $res = M('b2c_special_type_store')->where(['type_id' => $ids, "local_id" => session('userInfo')['local_id']])->delete();
        if ($res !== false) {
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    /**
     * 专题模板预览
     */
    public function viewTemplate()
    {
        $template_id = I('param.template_id');
        if (!$template_id) {
            $this->error('缺少参数');
        }
        //后台预览不需要走微信的分享授权
        /*$jssdk = new JssdkEvent();
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);*/
        $specialModel = new SpecialViewModel();
        $specialModel->template_id = $template_id;
        $data = $specialModel->viewTemplate();
        $this->assign($data);
        $this->display('viewTemplate');
    }
    /**
     * 专题预览
     */
    public function viewSpecial() {
        $id = I('param.id');
        if (!$id) {
            $this->error('缺少参数');
        }
        //后台预览不需要走微信的分享授权
        /*$jssdk = new JssdkEvent();
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);*/
        $specialModel = new SpecialViewModel();
        $specialModel->id = $id;
        $data = $specialModel->viewSpecial();
        $this->assign($data);
        $this->display('viewTemplate');
    }

    public function getProducts() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 15);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $local_id = session('userInfo')['local_id'];
        $where[] = array('a.local_id' =>  $local_id);
        $where[] = array('a.store_status' => 'true');
        $where[] = array('c.disabled' =>  'false');
        $where[] = array('d.product_type_id' =>  1);
        if ($search && $search_field) {
            if ($search_field == 'bn') {
                $sfield = 'a.'.$search_field;
            } else {
                $sfield = $search_field;
            }
            $where[] = $sfield." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_store_product a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id=d.product_id')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = 'a.*,b.`cat_name`,c.`name`,c.`barcode`,c.`spec_info`';
        $list = M('b2c_store_product a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id=d.product_id')
            ->field($fields)
            ->where($where)
            ->order($order)
            ->page($p, $num)
            ->select();
        //标记出已经选中的货品
        $type_id = I('param.type_id');
        if ($type_id) {
            $where = array('local_id'=>$local_id, 'type_id' => $type_id);
            $goodids = M('b2c_special_type_store')->where($where)->getField('goodids');
            if ($goodids) {
                $goodids = unserialize($goodids);
                foreach ($list as &$item) {
                    if (in_array($item['store_pid'], $goodids)) {
                        $item['is_show'] = true;
                    } else {
                        $item['is_show'] = false;
                    }
                }
            }
        }

        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function getSearchCart() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $word = I('get.word');
        $where[] = array('local_id' => session('userInfo')['local_id']);
        if (!empty($word)) {
            $where[] = "type_name like '%".$word."%'";
        }
        $res = M('b2c_special_type_store')
            ->where($where)
            ->field('type_name,type_id')
            ->select();
        if ($res !== false) {
            $return = array(
                'status' => true,
                'message' => '成功',
                'data' => $res,
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }



    /**
     *  专题广告模块你
     *
     */

    /*
     * 显示广告列表
     */

    public function advert()
    {
        $local_id = session('userInfo')['local_id'];
        $SpecialAdvertModel = M('qgs_special_advert');
        $row =  $SpecialAdvertModel->where("local_id='{$local_id}'")->order(array('order'=>'asc'))->select();
        $this->assign('rows',$row);
        $this->display('advert');
    }

    /**
     * 添加广告
     */
    public function advertAdd()
    {
        if (!IS_POST) {
            $this->display('advertadd');
        }else{
        $img = I('img', '', htmlspecialchars());
        $name = I('name', '', htmlspecialchars());
        $url = I('url', '', htmlspecialchars());
    //    $start_time = I('start_time', '', htmlspecialchars());
        $order = I('order', '', htmlspecialchars());
        $status = I('status', '', htmlspecialchars());
     //   $end_time = I('end_time', '', htmlspecialchars());
       $data = array(
           'local_id'=> session('userInfo')['local_id'],
           'name' => $name,
           'url'=>$url,
           'order' =>$order,
           'status'=>$status,
          // 'start_time' =>strtotime($start_time),
           'image'=>$img,
           'create_time'=>time(),
        //   'end_time'=>strtotime($end_time)
       );
      // 实例化数据模型
        $SpecialAdvertModel = M('qgs_special_advert');
        if ($SpecialAdvertModel->add($data) ===false) {
             $this->error('添加失败');
        }
        $this->success('添加成功',U('advert'));
     }
    }




    /**
     * 修改广告
     */
    public function advertedit()
    {  $SpecialAdvertModel = M('qgs_special_advert');
        if (!IS_POST) {
            $id = I('get.id',0);
            $row = $SpecialAdvertModel->find($id);
            $this->assign($row);
            $this->display('advertedit');
        }else{
            $id = I('id', '', htmlspecialchars());
            $name = I('name', '', htmlspecialchars());
            $url = I('url', '', htmlspecialchars());
         //   $start_time = I('start_time', '', htmlspecialchars());
            $order = I('order', '', htmlspecialchars());
            $status = I('status', '', htmlspecialchars());
         //   $end_time = I('end_time', '', htmlspecialchars());
            $rowimg = $SpecialAdvertModel->field('image')->find($id);
            $img = I('img', '', htmlspecialchars());
            if (empty($img)) {
                $img=$rowimg['image'];
            }

            $data = array(
                'id'=>  $id,
                'local_id'=> session('userInfo')['local_id'],
                'name' => $name,
                'url'=>$url,
                'order' =>$order,
                'status'=>$status,
             //   'start_time' =>strtotime($start_time),
                'image'=>$img,
                'create_time'=>time(),
             //   'end_time'=>strtotime($end_time)
            );
            if ($SpecialAdvertModel->save($data) ===false) {
                $this->error('修改失败');
            }
            $this->success('修改成功',U('advert'));
        }
    }

    /**
     * 删除 广告
     */


    public function advertdelete()
    {
        $id = I('post.id');
        if (M('qgs_special_advert')->delete($id) ===false) {
            ajax_json(false,'删除失败');
        }
            ajax_json(true,'删除成功');
    }


    /**
     * 修改关键字状态 开启/关闭
     */
    public function change() {
        if (!IS_AJAX) {
            $this->error('非法请求');
        }
        $id = I('get.id');
        $status = I('get.status');
        $status = $status == 'true' ? '1': '0';
        $res = M('qgs_special_advert')->where(['id'=>$id])->save(['status'=>$status]);
        if ($res !== false) {
            ajax_json(true,'成功');
        } else {
            ajax_json(true,'失败');
        }
    }



    /**
     * 推送广告给店铺
     */
    public function advertPush()
    {
        $sta = I('get.num')?I('get.num'):1;
        $advert = M('qgs_special_advert')->where(['status'=>1])->field('id,local_id')->select();
        $local_id = M('webpos_local_store')->field('local_id')->select();
        $advertstatus = M('qgs_special_advertstatus');
        $advert_id=[];
        foreach($advert as $g){
            $advert_id[]=$g['id'];
        }
         shuffle($advert_id);
        $advernum = count($advert);
        if ($sta>=$advernum) {
            $sta=$advernum;
        }
        $num =[];
        for($i = 1;$i<=$sta;$i++){
            $num[]=$i;
        }
        $advertstatus->where(1)->delete(); //分配前先情况原先的分配
        foreach($local_id as $i){
                foreach($num as $c){
                    $data=[
                        'local_id'=> $i['local_id'] ,
                        'advert_id'=>$this->getARandLetter(1,$advert_id)
                    ];
                 $advertstatus->add($data);
                }
        }

          ajax_json(true,'分配成功');

    }


    function getARandLetter($number = 1,$advert_id) {
        if ($number == 0)
            return FALSE; //去除0
         $number = $number < 0 ? - $number : $number; //如果小于零取正值
         $count = count($advert_id);
         $returnStr ='';

        for($i= 0; $i < $number; $i ++) {
            $returnStr= $advert_id [rand ( 0, $count-1)];
        }
        return $returnStr;
    }




}